package com.intramirror.product.controller;

import com.intramirror.core.common.response.Response;
import com.intramirror.product.entity.UserCertificate;
import com.intramirror.product.enums.CouponExportColumnEnum;
import com.intramirror.product.service.ICouponService;
import com.intramirror.product.utils.ExcelUtil;
import com.intramirror.product.vo.CouponInputVO;
import com.intramirror.product.vo.CouponQueryResponseVO;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

/**
 * Created by 123 on 2018/2/24.
 */
@RestController
public class CouponController {

    private final static Logger LOGGER = LoggerFactory.getLogger(CouponController.class);

    private static DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    ICouponService iCouponService;

    @PostMapping(value = "/coupon/batchInsert")
    public Response updateSpuById(@SessionAttribute(value = "user") Map<String, Object> user,
                                  @RequestBody CouponInputVO inputVO) {
        Long startDate = inputVO.getStartDate();
        Long endDate = inputVO.getEndDate();
        if(startDate==null||endDate==null){
            throw new IllegalArgumentException("startDate or endDate is null");
        }
        List<UserCertificate> list = new ArrayList<>();
        List<Map<String, String>> mapList = inputVO.getList();
        if (mapList!=null&&mapList.size()>0){
            LOGGER.info("此次批量发送代金券数量为{}",mapList.size());
            for(Map<String,String> map:mapList){
                UserCertificate certificate = new UserCertificate();
                certificate.setAmount(inputVO.getMoney());
                certificate.setEffectiveDate(new Date(startDate));
                certificate.setUserId(Long.valueOf(map.get("userId")));
                certificate.setExpirationDuration((endDate-startDate)/1000); //生效时长（单位s）
                certificate.setIssuedBy((Long) user.get("userId"));
                list.add(certificate);
            }
        }
        iCouponService.batchInsertCoupon(list);
        return Response.success();
    }

    @PostMapping(value = "/coupon/selectCoupons")
    public Response selectCoupons(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        List<CouponQueryResponseVO> responseVOs = new ArrayList<>();

        Map<String, Object> queryCondition = generateQueryCondition(params);

        Integer pageNo = params.get("pageNo") == null ? 1 : Integer.parseInt(params.get("pageNo").toString());
        Integer pageSize = params.get("pageSize") == null ? 20 : Integer.parseInt(params.get("pageSize").toString());

        int start = pageNo < 1 ? 0 : (pageNo - 1) * pageSize;
        int limit = pageSize < 1 ? 20 : pageSize;
        queryCondition.put("start", start);
        queryCondition.put("limit", limit);

        int totalNum = iCouponService.countCouponUserList(queryCondition);
        if (totalNum == 0) {
            result.put("list", responseVOs);
            result.put("totalNum", totalNum);
            return Response.status(1).data(result);
        }
        responseVOs = iCouponService.queryCouponUserList(queryCondition);

        result.put("list", responseVOs);
        result.put("totalNum", totalNum);
        return Response.status(1).data(result);
    }

    private Map<String, Object> generateQueryCondition(Map<String, Object> params) {
        Map<String, Object> queryCondition = new HashMap<>();

        if (stringParamCheck(params.get("nameTel"))) {
            queryCondition.put("nameTel", params.get("nameTel"));
        }
        if (stringParamCheck(params.get("amountMin"))) {
            queryCondition.put("amountMin", params.get("amountMin"));
        }
        if (stringParamCheck(params.get("amountMax"))) {
            queryCondition.put("amountMax", params.get("amountMax"));
        }
        if (stringParamCheck(params.get("couponType"))) {
            queryCondition.put("couponType", params.get("couponType"));
        }
        if (stringParamCheck(params.get("status"))) {
            queryCondition.put("status", params.get("status"));
        }
        if (stringParamCheck(params.get("operator"))) {
            queryCondition.put("operator", params.get("operator"));
        }
        if (stringParamCheck(params.get("relatedOrderNum"))) {
            queryCondition.put("relatedOrderNum", params.get("relatedOrderNum"));
        }
        if (stringParamCheck(params.get("usedDateMin"))) {
            Date usedDateMinDate = new Date(Long.parseLong(params.get("usedDateMin").toString()));
            queryCondition.put("usedDateMin", usedDateMinDate);
        }
        if (stringParamCheck(params.get("usedDateMax"))) {
            Date usedDateMaxDate = new Date(Long.parseLong(params.get("usedDateMax").toString()));
            queryCondition.put("usedDateMax", usedDateMaxDate);
        }
        if (stringParamCheck(params.get("releaseDateMin"))) {
            Date releaseDateMinDate = new Date(Long.parseLong(params.get("releaseDateMin").toString()));
            queryCondition.put("releaseDateMin", releaseDateMinDate);
        }
        if (stringParamCheck(params.get("releaseDateMax"))) {
            Date releaseDateMaxDate = new Date(Long.parseLong(params.get("releaseDateMax").toString()));
            queryCondition.put("releaseDateMax", releaseDateMaxDate);
        }
        return queryCondition;
    }

    private boolean stringParamCheck(Object obj) {
        return obj != null && StringUtils.isNotEmpty(obj.toString());
    }

    @PostMapping(value = "/coupon/exportCoupons")
    public Response exportCoupons(@RequestBody Map<String, Object> params, HttpServletResponse response) {
        Map<String, Object> queryCondition = generateQueryCondition(params);

        List<CouponQueryResponseVO> responseVOs = iCouponService.queryCouponUserList(queryCondition);

        //获取代金券导出数据的表头
        CouponExportColumnEnum[] columnEnums = CouponExportColumnEnum.values();
        List<ExcelUtil.ExcelVo> header = getExcelVos(columnEnums);

        try {
            ExcelUtil.toExcelOutStream(response, "代金券数据导出", header, responseVOs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Response.success();
    }

    private List<ExcelUtil.ExcelVo> getExcelVos(CouponExportColumnEnum[] columnEnums) {
        List<ExcelUtil.ExcelVo> header = new ArrayList<ExcelUtil.ExcelVo>();
        for (CouponExportColumnEnum columnEnum : columnEnums) {
            ExcelUtil.ExcelVo ev = new ExcelUtil.ExcelVo(columnEnum.getChineseName(), HSSFCell.CELL_TYPE_STRING,
                    columnEnum.getEnglishName());
            header.add(ev);
        }
        return header;
    }
}
